/**
 * 数据看板控制器 - 处理企业财务数据统计和可视化数据的REST API接口
 *
 * 开发人员：徐少洋
 * 开发时间：2025-10-25 至 2025-10-28
 * 模块职责：提供企业财务数据统计和可视化数据的REST API接口，支持仪表板数据展示和性能监控
 *
 * 技术要点：
 * - RESTful API设计，遵循REST规范
 * - 多租户架构，企业级数据隔离
 * - 缓存机制优化统计查询性能
 * - 实时数据统计和聚合计算
 * - 日期范围计算和时间筛选
 *
 * 开发故事：负责数据看板控制器的开发，与前端数据可视化组件深度配合，为企业管理者提供直观的数据洞察和决策支持。
 */
package com.pbl.controller;

import com.pbl.common.model.ApiResponse;
import com.pbl.repository.PaymentOrderRepository;
import com.pbl.util.DateRangeUtil;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/enterprises/{enterpriseId}/dashboard")
public class DashboardController {

    private final PaymentOrderRepository paymentOrderRepository;

    /**
     * 构造数据看板控制器
     * @param paymentOrderRepository 支付订单数据访问层
     */
    public DashboardController(PaymentOrderRepository paymentOrderRepository) {
        this.paymentOrderRepository = paymentOrderRepository;
    }

    /**
     * 获取仪表板统计数据
     * 缓存5分钟，按企业ID和日期缓存
     */
    @GetMapping("/metrics")
    @Cacheable(value = "dashboard:metrics", key = "#enterpriseId + ':' + T(java.time.LocalDate).now()")
    public ApiResponse<Map<String, Object>> metrics(@PathVariable Long enterpriseId) {
        LocalDateTime start = DateRangeUtil.todayStart();
        LocalDateTime end = DateRangeUtil.todayEnd();
        
        long totalToday = paymentOrderRepository.countByEnterprise_IdAndCreatedAtBetween(enterpriseId, start, end);
        long successToday = paymentOrderRepository.countByEnterprise_IdAndStatusAndCreatedAtBetween(enterpriseId, com.pbl.common.enums.PaymentStatus.SUCCESS, start, end);
        BigDecimal amountToday = paymentOrderRepository.sumSuccessAmountBetween(enterpriseId, start, end);

        Map<String, Object> metrics = new HashMap<>();
        metrics.put("ordersToday", totalToday);
        metrics.put("successToday", successToday);
        metrics.put("successAmountToday", amountToday);
        
        return ApiResponse.success(metrics);
    }
}
